package com.han.gift.common.exception.handler;

import com.han.gift.common.exception.BusinessException;
import com.han.gift.common.exception.Erroenum.ErrorCode;
import com.han.gift.common.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author:Han
 * @Date :2023/2/27 18:02
 * @Description:
 */
@RestControllerAdvice
public class GlobalExceptionHandler {



    //服务异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult BusinessExceptionHandler(BusinessException e){

        e.printStackTrace();
       return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(e.getCode());

    }

    //捕获验证参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        StringBuffer sb = new StringBuffer();
        fieldErrors.forEach(error->{
            String field= error.getField();
            String message = error.getDefaultMessage();
            sb.append(field).append(message).append(",");
        });
        return AjaxResult.me()
                .setSuccess(false)
                .setCode(ErrorCode.CODE_400_PARAM_VALID.getCode())
                .setMessage(sb.toString());
    }

    //所有异常
    @ExceptionHandler(Exception.class)
    public AjaxResult ExceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode());
    }


}
